<?php

namespace app\logic;

use app\model\Workorder as WorkOrderModel;
use common\util\PagingUtil;
use think\db\Query;
use think\facade\Db;

class WorkOrderLogic
{
    /**
     * @var WorkOrderModel
     */
    private WorkOrderModel $workOrderModel;

    /**
     * @var OptionLogic
     */
    private OptionLogic $optionLogic;

    /**
     * @var FlowSetLogic
     */
    private FlowSetLogic $flowSetLogic;

    /**
     * 模块编号
     *
     * @var string
     */
    private string $num = 'workorder';

    /**
     * @param WorkOrderModel $workOrderModel
     * @param OptionLogic $optionLogic
     * @param FlowSetLogic $flowSetLogic
     */
    public function __construct(WorkOrderModel $workOrderModel, OptionLogic $optionLogic, FlowSetLogic $flowSetLogic)
    {
        $this->workOrderModel = $workOrderModel;
        $this->optionLogic = $optionLogic;
        $this->flowSetLogic = $flowSetLogic;
    }


    /**
     * @return array
     */
    public function getTypeOption(): array
    {
        return $this->optionLogic->getSelectOption('worktype');
    }

    /**
     * @return array
     */
    public function getPriorityOption(): array
    {
        $mid = $this->flowSetLogic->getMid($this->num);
        $optionData = Db::name('flow_element')
            ->where('mid', $mid)
            ->where('fields', 'priority')
            ->value('data');

        if (!empty($optionData)) {
            $optionData = explode(',', $optionData);
        } else {
            $optionData = [];
        }

        return $optionData;
    }

    public function getList(array $params)
    {
        $pagingEntity = PagingUtil::builder($params);
        return $this->workOrderModel
            ->with([
                WorkOrderModel::BILL => function (Query $query) {
                    $query->field('mid,uname as base_name,udeptname as base_deptname,sericnum,nowcheckname');
                    $query->where('table', $this->num);
                }
            ])
            ->order('id', 'desc')
            ->paginate($pagingEntity->getPaginateCondition());
    }
}